package kn.cstf2.assign.Client;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.Map;
import kn.cstf2.assign.Bean.ListaTablaBean;
import kn.cstf2.assign.Bean.T_usersBean;
import kn.cstf2.assign.Shared.AssignShared;
import kn.cstf2.global.Utils.CstF2Exception;
import kn.cstf2.transition.Bean.TransitionBean;
import kn.mx.cstf2.dto.UsuarioDto;

import org.apache.log4j.Logger;

public class AssignAction extends ActionSupport {

    private static Logger log = Logger.getLogger(AssignAction.class);
    public static final String ERROR_SESSION = "errorSession";
    public static final String ERROR_KNKEY = "errorKnkey";
    public static final String ERROR_SAME_KNKEYS = "errorSameKnkeys";
    public static final String ASSIGN = "asign";
    public static final String NOEXISTEKNKEY = "noexisteknkey";
    public static final String SEARCH = "search";
    public static final String SEARCHRESULT = "searchResult";
    private TransitionBean transitionBeanM = new TransitionBean();
    private String nombreocorreo = "";
    private String textBuscar;
    private String txtCompanyNames;
    private int idUsuarioLike;
    private int idKnkey;
    private int direccionAction;
    private ArrayList<Integer> idTransitionArray = new ArrayList<Integer>();
    private ArrayList<T_usersBean> listaNombres = new ArrayList<T_usersBean>();
    private ArrayList<ListaTablaBean> listaTable = new ArrayList<ListaTablaBean>();
    private Integer knkey;
    private Integer idName;
    private String newKnkeys;

    public int getDireccionAction() {
        return direccionAction;
    }

    public void setDireccionAction(int direccionAction) {
        this.direccionAction = direccionAction;
    }

    public String getTextBuscar() {
        return textBuscar;
    }

    public void setTextBuscar(String textBuscar) {
        this.textBuscar = textBuscar;
    }

    public int getIdUsuarioLike() {
        return idUsuarioLike;
    }

    public String getTxtCompanyNames() {
        return txtCompanyNames;
    }

    public void setTxtCompanyNames(String txtCompanyNames) {
        this.txtCompanyNames = txtCompanyNames;
    }

    public void setIdUsuarioLike(int idUsuarioLike) {
        this.idUsuarioLike = idUsuarioLike;
    }

    public int getIdKnkey() {
        return idKnkey;
    }

    public void setIdKnkey(int idKnkey) {
        this.idKnkey = idKnkey;
    }

    public String getNewKnkeys() {
        return newKnkeys;
    }

    public void setNewKnkeys(String newKnkeys) {
        this.newKnkeys = newKnkeys;
    }

    public ArrayList<ListaTablaBean> getListaTable() {
        return listaTable;
    }

    public void setListaTable(ArrayList<ListaTablaBean> listaTable) {
        this.listaTable = listaTable;
    }

    public Integer getIdName() {
        return idName;
    }

    public void setIdName(Integer idName) {
        this.idName = idName;
    }

    public ArrayList<T_usersBean> getListaNombres() {
        return listaNombres;
    }

    public void setListaNombres(ArrayList<T_usersBean> listaNombres) {
        this.listaNombres = listaNombres;
    }

    public ArrayList<Integer> getIdTransitionArray() {
        return idTransitionArray;
    }

    public void setIdTransitionArray(ArrayList<Integer> idTransitionArray) {
        this.idTransitionArray = idTransitionArray;
    }

    public Integer getKnkey() {
        return knkey;
    }

    public void setKnkey(Integer knkey) {
        this.knkey = knkey;
    }

    public String getNombreocorreo() {
        return nombreocorreo;
    }

    public void setNombreocorreo(String nombreocorreo) {
        this.nombreocorreo = nombreocorreo;
    }

    public TransitionBean getTransitionBeanM() {
        return transitionBeanM;
    }

    public void setTransitionBeanM(TransitionBean transitionBeanM) {
        this.transitionBeanM = transitionBeanM;
    }

    public AssignAction() {
//        AssignShared assignShared = new AssignShared();
//        setListaNombres(assignShared.GetListaNombresDataFromTusers(nombreocorreo));
//        setListaTable(assignShared.GetListaTabla(idName));
    }

    public String execute() {
        switch (direccionAction) {
            case 1:
                return SEARCH;
            case 2:
                return ASSIGN;
        }

        UsuarioDto usuario = new UsuarioDto();
        ActionContext contexto = ActionContext.getContext();
        Map<String, Object> sesion = contexto.getSession();
        usuario = (UsuarioDto) sesion.get("usuarioSession");
        Map<String, Object> sesion2 = contexto.getSession();
        transitionBeanM = (TransitionBean) sesion2.get("Knkey");
        try {
        } catch (CstF2Exception ex) {
            log.error("ERROR. ", ex);
            addFieldError("KnkeyIncorrecta", "Ocurrio un Error: " + ex.getMessage());
            return ERROR_SESSION;
        }



        return SUCCESS;
    }

    public String ConsultaNombresLike() {
        try {
            AssignShared assignShared = new AssignShared();

            listaNombres = assignShared.GetListaNombresDataFromTusers(getTextBuscar().toLowerCase());


        } catch (CstF2Exception ex) {
            log.error("ERROR. ", ex);
            addFieldError("KnkeyIncorrecta", "Ocurrio un Error: " + ex.getMessage());
            return ERROR_SESSION;
        }
        return SEARCHRESULT;
    }

    public String ConsultaKnkeys() {
        try {
            AssignShared assignShared = new AssignShared();
            T_usersBean t_usersBean = new T_usersBean();
            Integer iduser = 0;

            setListaNombres(assignShared.GetListaNombresDataFromTusers(nombreocorreo));
            iduser = t_usersBean.getId();
            assignShared.GetAllKnkeys(iduser);


            ActionContext contexto = ActionContext.getContext();
            Map<String, Object> sesionName = contexto.getSession();
            sesionName.put("idUserName", idName);

        } catch (CstF2Exception ex) {
            log.error("ERROR. ", ex);
            addFieldError("KnkeyIncorrecta", "Ocurrio un Error: " + ex.getMessage());
            return ERROR_SESSION;
        }
        return SUCCESS;
    }

    public String ConsultaUserForNameoMail() {
        try {
            AssignShared assignShared = new AssignShared();
            T_usersBean t_usersBean = new T_usersBean();
            Integer iduser = 0;

            t_usersBean = assignShared.GetDataFromTusers(nombreocorreo);
            iduser = t_usersBean.getId();
            assignShared.GetAllKnkeys(iduser);


        } catch (CstF2Exception ex) {
            log.error("ERROR. ", ex);
            addFieldError("KnkeyIncorrecta", "Ocurrio un Error: " + ex.getMessage());
            return ERROR_SESSION;
        }
        return SUCCESS;
    }

    public String AgregarNuevosKnkeysToUser() {
        try {
            ActionContext contexto = ActionContext.getContext();
            Map<String, Object> sesionName = contexto.getSession();
            Integer idNombre = (Integer) sesionName.get("sessionIdUsuarioLike");

            int bandera = 0;
            AssignShared assignShared = new AssignShared();
            String knkeysCorreo = "";
            String nuevasKnkeys = getNewKnkeys();
            String companyName = getTxtCompanyNames();
            nuevasKnkeys.trim();

            String splitChar = ",";
            if (nuevasKnkeys.contains(",") || companyName.contains(",")) {
                splitChar = ",";
            }
            if (nuevasKnkeys.contains(";") || companyName.contains(";")) {
                splitChar = ";";
            }
            if (nuevasKnkeys.contains("-") || companyName.contains("-")) {
                splitChar = "-";
            }

            String novasKnkeys[] = nuevasKnkeys.split(splitChar);
            Integer novasKnkeysInt[] = new Integer[novasKnkeys.length];
            ArrayList<Integer> oldKnkeys = assignShared.GetAllKnkeys(idNombre);
            ArrayList<Integer> insertKnkeys = new ArrayList<Integer>();

            if (nuevasKnkeys.length() == 0) {
            } else {
                for (int i = 0; i < novasKnkeys.length; i++) {
                    novasKnkeysInt[i] = Integer.parseInt(novasKnkeys[i]);
                }
                if (oldKnkeys.size() == 0) {
                    int contador = 0;
                    for (Integer novaKnkey : novasKnkeysInt) {
                        if ((assignShared.ExisteKnkeyEnTClientes(novaKnkey) == true) && (assignShared.ExisteKnkeyEnTRansition(novaKnkey) == true)) {
                            insertKnkeys.add(novaKnkey);
                            if (contador == 0) {
                                knkeysCorreo += novaKnkey;
                            } else {
                                knkeysCorreo += ", " + novaKnkey;
                            }
                            contador++;
                        }
                    }
                } else {
                    for (Integer novaKnkey : novasKnkeysInt) {
                        int contador = 0;
                        if (!oldKnkeys.contains(novaKnkey) && (assignShared.ExisteKnkeyEnTClientes(novaKnkey) == true) && (assignShared.ExisteKnkeyEnTRansition(novaKnkey) == true)) {
                            insertKnkeys.add(novaKnkey);
                        }
                        if (contador == 0) {
                            knkeysCorreo += novaKnkey + " ";
                        } else {
                            knkeysCorreo += ", " + novaKnkey;
                        }
                        contador++;
                    }
                }

                if (insertKnkeys.size() != 0) {
                    ArrayList<Integer> idTransitions = assignShared.GetIdTransition(insertKnkeys);
                    assignShared.InsertRelationUserKnkey(idNombre, idTransitions);
                    sendEmail(knkeysCorreo, companyName);
                }
            }

            listaTable = assignShared.GetListaTabla(idNombre);

        } catch (CstF2Exception ex) {
            log.error("ERROR. ", ex);
            addFieldError("KnkeyIncorrecta", "Ocurrio un Error: " + ex.getMessage());
            return ERROR_SESSION;
        }
        return ASSIGN;
    }

    public String DeleteRelationUserKnkey() {
        ActionContext contexto = ActionContext.getContext();
        Map<String, Object> sesionName = contexto.getSession();
        Integer idNombreUsuario = getIdUsuarioLike();
        try {
            AssignShared assignShared = new AssignShared();
            Integer idTransition = assignShared.GetOneIdTransition(getIdKnkey());
            assignShared.DeleteRelationUserKnkey(idNombreUsuario, idTransition);
            listaTable = assignShared.GetListaTabla(idNombreUsuario);


        } catch (CstF2Exception ex) {
            log.error("ERROR. ", ex);
            addFieldError("KnkeyIncorrecta", "Ocurrio un Error: " + ex.getMessage());
            return ERROR_SESSION;
        }
        return ASSIGN;
    }

    public void GuardarIdNameOnSession() {
        ActionContext contexto = ActionContext.getContext();
        Map<String, Object> sesionName = contexto.getSession();
        sesionName.put("idUserName", idName);
    }

    public static void sendEmail(String knkeys, String companyName) {
        ActionContext contexto = ActionContext.getContext();
        Map<String, Object> sesionName = contexto.getSession();
        Integer idNombreUsuario = (Integer) sesionName.get("sessionIdUsuarioLike");
        try {
            T_usersBean idTransition = new T_usersBean();
            AssignShared assignShared = new AssignShared();
            idTransition = assignShared.GetDataUsersFromId(idNombreUsuario);

            String correoUser = idTransition.getEmail();

            MailSender correo = new MailSender();
            ArrayList<String> direcciones = new ArrayList<String>();
            StringBuilder mensaje = new StringBuilder();
            mensaje.append("Please be adviced that the following KNKEY and customer has been assigned to your account. \n");
            mensaje.append("KNKEY: ");
            mensaje.append(knkeys);
            mensaje.append(" \n");
            mensaje.append("COMPANYNAME: ");
            mensaje.append(companyName);

            direcciones.add(correoUser);
            
            System.out.println(mensaje);
            correo.sendEmail(direcciones, "Assignes transition implementation confirmation (" + companyName + ")", mensaje);

        } catch (CstF2Exception ex) {
            log.error("ERROR. ", ex);
        }

    }

    public String AsignarKnekeys() {
        AssignShared assignShared = new AssignShared();
        listaTable = assignShared.GetListaTabla(getIdUsuarioLike());
        ActionContext contexto = ActionContext.getContext();
        Map<String, Object> sesionName = contexto.getSession();
        sesionName.put("sessionIdUsuarioLike", getIdUsuarioLike());

        return ASSIGN;
    }

    public String MostrarCompanysName() {
        AssignShared assignShared = new AssignShared();
        listaTable = assignShared.GetListaTabla(getIdUsuarioLike());
        ActionContext contexto = ActionContext.getContext();
        Map<String, Object> sesionName = contexto.getSession();
        Integer idNombre = (Integer) sesionName.get("sessionIdUsuarioLike");
        sesionName.put("sessionTextKnekeys", getNewKnkeys());

        String nuevasKnkeys = getNewKnkeys();
        nuevasKnkeys = nuevasKnkeys.trim();

        String splitChar = ",";
        if (nuevasKnkeys.contains(",")) {
            splitChar = ",";
        }
        if (nuevasKnkeys.contains(";")) {
            splitChar = ";";
        }
        if (nuevasKnkeys.contains("-")) {
            splitChar = "-";
        }

        String novasKnkeys[] = nuevasKnkeys.split(splitChar);
        Integer novasKnkeysInt[] = new Integer[novasKnkeys.length];
        ArrayList<Integer> oldKnkeys = assignShared.GetAllKnkeys(idNombre);
        ArrayList<Integer> insertKnkeys = new ArrayList<Integer>();
        Boolean existe = true;
        try {
            if (novasKnkeys.length == 0) {
            } else {
                for (int y = 0; y < novasKnkeys.length; y++) {
                    novasKnkeysInt[y] = Integer.parseInt(novasKnkeys[y]);
                }
                if (oldKnkeys.size() == 0) {
                    for (Integer novaKnkey : novasKnkeysInt) {
                        if ((assignShared.ExisteKnkeyEnTClientes(novaKnkey)) && (assignShared.ExisteKnkeyEnTRansition(novaKnkey))) {
                            insertKnkeys.add(assignShared.GetKnkeyFromTClientes(novaKnkey));
                        }
                    }
                } else {
                    for (Integer novaKnkey : novasKnkeysInt) { //aqui me pasa lo q le pasaba a fer de que se llegan a cruzar y combiar los numeros asi q hay q ponerle banderas
                        if (assignShared.ExisteKnkeyEnTClientes(novaKnkey) && !oldKnkeys.contains(novaKnkey)) {
                            Integer k = assignShared.GetKnkeyFromTClientes(novaKnkey);
                            insertKnkeys.add(k);
                        }
                    }
                }

                setTxtCompanyNames(assignShared.GetAllCompanyNames(insertKnkeys));


            }

            listaTable = assignShared.GetListaTabla(idNombre);

        } catch (NumberFormatException ex) {
            log.error("ERROR. ", ex);
        } catch (CstF2Exception ex) {
            log.error("ERROR. ", ex);
            addFieldError("KnkeyIncorrecta", "Ocurrio un Error: " + ex.getMessage());

        }

        return ASSIGN;
    }
}